import React, { useState, useContext, ReactElement, FC } from 'react'
import { useSelector } from 'react-redux'
import { IRootReducers } from '@/reducers'
import Taro from '@tarojs/taro'
import { 
  Map, 
  Button, 
  View, 
  Text, 
  Image, 
  Swiper, 
  SwiperItem
} from '@tarojs/components'
import TemplateStyle from './Template1.module.scss'

const tipEn = 'WE LOOK FORWARD TO YOUR COMING TO OUR WEDDING'

const SwiperContext = React.createContext(0)

// 模板组件默认props值
const defaultProps = { pageIndex: 0 }

// 生成props的类型
type IProps = typeof defaultProps

/**
 * 主模板，带上背景和花花草草的
 * @param props 组件传参
 */
const TemplateFrame: FC<IProps> = (props = defaultProps) => {
  // 当前需要展示的索引
  const showIndex = useContext<number>(SwiperContext)
  // 当前是否是激活状态
  const isActive = (showIndex + 1 === props.pageIndex)
  return (
    <SwiperItem className={TemplateStyle['page-wrap']}>
      <View className={TemplateStyle.page}>
        {props.children}
        <View className={[TemplateStyle.grass2, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
        <View className={[TemplateStyle.grass1, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
        <View className={[TemplateStyle.grass5, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
        <View className={[TemplateStyle.grass3, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
        <View className={[TemplateStyle.grass4, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
        <View className={[TemplateStyle.grass6, 'animated', isActive ? 'rotate-quarter-reverse' : ''].join(' ')} />
        <View className={[TemplateStyle.grass7, 'animated', isActive ? 'rotate-quarter-reverse' : ''].join(' ')} />
        <View className={[TemplateStyle.grass8, 'animated', isActive ? 'rotate-quarter-reverse' : ''].join(' ')} />
        <View className={[TemplateStyle.grass9, 'animated', isActive ? 'rotate-quarter' : ''].join(' ')} />
      </View>
    </SwiperItem>
  )
}

/**
 * 有黄金框背景的模板，包裹于TemplateFrame组件
 * @param props 组件传参
 */
const GoldenTemplateFrame: FC<IProps> = (props = defaultProps) => {
  // 当前需要展示的索引
  const showIndex = useContext(SwiperContext)
  // 当前是否是激活状态
  const isActive = (showIndex + 1 === props.pageIndex)
  return (
    <TemplateFrame pageIndex={props.pageIndex}>
      <View className={TemplateStyle['golden-wrap']}>
        <View className={TemplateStyle['detail-wrap']}>
          {props.children}
          <View className={[TemplateStyle.tip, TemplateStyle.small, 'animated, delay-500', isActive ? 'scale-to-normal' : ''].join(' ')}>{tipEn}</View>
          <View className={[TemplateStyle['golden-border'], 'animated', isActive ? 'rotate-quarter-reverse' : ''].join(' ')} />
          <View className={[TemplateStyle['golden-border'], 'animated', TemplateStyle.side, isActive ? 'rotate-quarter-more' : ''].join(' ')} />
        </View>
      </View>
    </TemplateFrame>
  )
}

function InvitationLetter({ active }): ReactElement | null {
  return <View className={[TemplateStyle.tip, TemplateStyle.split, 'animated delay-500', active ? 'scale-to-normal' : ''].join(' ')}>{'INVITATIONLETTER'.split('').map((item, index) => <Text key={`item_${index}`}>{item}</Text>)}</View>
}

function Template(): ReactElement | null {
  const vertical = true
  const lazyLoad = true

  /**
   * 拨打电话
   */
  const handleMakePhoneCall = (phoneNumber: string) => {
    Taro.makePhoneCall({ phoneNumber })
  }

  /**
   * 打开地图搜索
   */
  const handleOpenMap = () => {
    Taro.openLocation({
      latitude: 31.477724,
      longitude: 116.941828,
      name: '盛世人和酒店'
    })
  }

  // 首页需要的数据
  const { pages, groom, bride, position, timeDate } = useSelector((state: IRootReducers) => state.home)
  // 当前swiper的索引
  const [ index, setSwiperIndex ] = useState<number>(0)
  // 节流点击方法
  const setSwiperIndexThrottle = debounce(changedIndex => setSwiperIndex(changedIndex), 200)
  return (
    <SwiperContext.Provider value={index}>
      <Swiper
        vertical={vertical}
        className={TemplateStyle.template}
        onChange={e => setSwiperIndex(e.detail.current)}
        current={index}
      >
        <TemplateFrame pageIndex={1}>
          <View className={TemplateStyle.home}>
            <View className={TemplateStyle.container}>
              <View className={TemplateStyle['avatar-wrap']}>
                <Image 
                  lazyLoad={lazyLoad}
                  className={[TemplateStyle.avatar, 'animated', 'delay-300', index == 0 ? 'scale-to-normal' : ''].join(' ')} 
                  src={pages[0].avatar || ''}
                  onClick={_ => Taro.navigateTo({ url: '/pages/wall/photo' })}
                />
              </View>
              <View className={[TemplateStyle['placeholder-icon'], 'animated delay-300 duration-long', index == 0 ? 'translate-y-up' : ''].join(' ')} />
              <View className={[TemplateStyle.time, 'animated delay-500 duration-long', index == 0 ? 'translate-y-up' : ''].join(' ')}>{pages[0].time}</View>
              <View className={[TemplateStyle.newlywed, 'animated delay-500 duration-long', index == 0 ? 'translate-y-up' : ''].join(' ')}>{pages[0].name}</View>
              <View className={[TemplateStyle.tip, TemplateStyle.small, 'animated delay-500 duration-long', index == 0 ? 'scale-to-normal' : ''].join(' ')}>{tipEn}</View>
              <View className={[TemplateStyle.tip, 'animated delay-500 duration-long', index == 0 ? 'translate-y-down' : ''].join(' ')}>诚邀您参加我们的婚礼</View>
            </View>
            <View className={[TemplateStyle['bg-image'], 'animated', index == 0 ? 'scale-to-normal' : ''].join(' ')} />
          </View>
        </TemplateFrame>
        <GoldenTemplateFrame pageIndex={2}>
          <>
            <View className={[TemplateStyle['image-wrap'], 'animated delay-300', index == 1 ? 'scale-to-normal' : ''].join(' ')}>
              <Image 
                className={TemplateStyle['image']}
                mode='aspectFill' 
                src={pages[1].avatar || ''}
              />
            </View>
            <InvitationLetter active={index == 1} />
            { // 遍历数据
              pages[1].data && pages[1].data.map((tip, dataIndex) => (
                <View 
                  key={`index_${dataIndex}`}
                  className={[
                    TemplateStyle[tip.style], 
                    `animated delay-${5 + dataIndex}00`, 
                    index == 1 ? 'translate-y-up' : ''
                    
                  ].join(' ')}
                >{tip.title}</View>
              ))
            }
            <View className={[TemplateStyle.footer, 'animated delay-500 duration-long', index == 1 ? 'scale-to-normal' : ''].join(' ')}>- 敬备喜酌   恭请光临 -</View>
          </>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={3}>
          <>
            <View className={[TemplateStyle['avatar-wrap'], 'animated delay-300 duration-long', index == 2 ? 'scale-to-normal' : ''].join(' ')}>
              <Image 
                mode='widthFix' 
                className={TemplateStyle.avatar} 
                src={groom.avatar}
              />
              <View className={[TemplateStyle['icon-groom'], 'animated delay-500', index == 2 ? 'translate-y-up' : ''].join(' ')} />
              <View className={[TemplateStyle.groom, 'animated delay-500', index == 2 ? 'translate-y-down' : ''].join(' ')}>新郎：{groom.name}</View>
            </View>
            <View className={TemplateStyle.quotation}>
              { // 遍历宣言
                pages[2].words && pages[2].words.map((word, dataIndex) => (
                  <View 
                    key={word}
                    className={[
                      TemplateStyle.row, 
                      `animated delay-${8 + dataIndex}00 duration-long`, 
                      index == 2 ? 'translate-y-up' : ''
                    ].join(' ')}
                  >{word}</View>
                ))
              }
            </View>
          </>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={4}>
          <>
            <View className={[TemplateStyle['avatar-wrap'], 'animated delay-300 duration-long', index == 3 ? 'scale-to-normal' : ''].join(' ')}>
              <Image 
                mode='widthFix' 
                className={TemplateStyle.avatar} 
                src={bride.avatar}
              />
              <View className={[TemplateStyle['icon-bride'], 'animated delay-500', index == 3 ? 'translate-y-up' : ''].join(' ')} />
              <View className={[TemplateStyle.bride, 'animated delay-500', index == 3 ? 'translate-y-down' : ''].join(' ')}>新娘：{bride.name}</View>
            </View>
            <View className={TemplateStyle.quotation}>
              { // 遍历宣言
                pages[3].words && pages[3].words.map((word, dataIndex) => (
                  <View 
                    key={word}
                    className={[
                      TemplateStyle.row, 
                      `animated delay-${8 + dataIndex}00 duration-long`, 
                      index == 3 ? 'translate-y-up' : ''
                    ].join(' ')}
                  >{word}</View>
                ))
              }
            </View>
          </>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={5}>
          <View className={TemplateStyle['image-group-column']}>
            <View className={[TemplateStyle['image-wrap'], 'animated delay-300 duration-long', index == 4 ? 'rotate-quarter-reverse-show' : ''].join(' ')}>
              <Image 
                className={TemplateStyle.image} 
                mode='aspectFill' 
                src={pages[4].avatars ? pages[4].avatars[0] : ''}
              />
            </View>
            <InvitationLetter active={index == 4} />
            <View className={[TemplateStyle['image-wrap'], 'animated delay-300 duration-long', index == 4 ? 'rotate-quarter-show' : ''].join(' ')}>
              <Image 
                className={TemplateStyle.image} 
                mode='aspectFill' 
                src={pages[4].avatars ? pages[4].avatars[1] : ''}
              />
            </View>
            <View className={[TemplateStyle.quotation, TemplateStyle.center, TemplateStyle['no-icon']].join(' ')}>
              {
                pages[4].words && pages[4].words.map((word, wordIndex) => (
                  <View 
                    key={word}
                    className={[
                      TemplateStyle.row, 
                      `animated delay-${8 + wordIndex}00 duration-long`, 
                      index == 4 ? 'translate-y-up' : ''
                    ].join(' ')}
                  >{word}</View>
                ))
              }
            </View>
          </View>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={6}>
          <>
            <View className={[TemplateStyle['image-group-grid'], 'animated, delay-300', index == 5 ? 'opacity' : ''].join(' ')}>
              <View className={TemplateStyle['column']}>
                <Image 
                  mode='aspectFill' 
                  className={[TemplateStyle['avatar'], 'animated, delay-300', index == 5 ? 'translate-x-right' : ''].join(' ')} 
                  src={pages[5].avatars ? pages[5].avatars[0] : ''} 
                />
              </View>
              <View className={TemplateStyle.column}>
                <Image 
                  mode='aspectFill' 
                  className={[TemplateStyle['avatar'], TemplateStyle['small'], 'animated, delay-300', index == 5 ? 'translate-x-left' : ''].join(' ')} 
                  src={pages[5].avatars ? pages[5].avatars[1] : ''}
                />
                <Image 
                  mode='aspectFill' 
                  className={[TemplateStyle['avatar'], TemplateStyle['small'], 'animated, delay-300', index == 5 ? 'translate-x-left' : ''].join(' ')} 
                  src={pages[5].avatars ? pages[5].avatars[2] : ''}
                />
              </View>
            </View>
            <View className={[TemplateStyle['icon-beauty'], 'animated delay-500', index == 5 ? 'scale-to-normal' : ''].join(' ')} />
            <View className={[TemplateStyle.quotation, TemplateStyle['no-icon']].join(' ')}>
              {
                pages[5].words && pages[5].words.map((word, wordIndex) => (
                  <View 
                    key={word}
                    className={[
                      TemplateStyle.row,
                      `animated delay-${8 + wordIndex}00 duration-long`,
                      index == 5 ? 'translate-y-up' : ''
                    ].join(' ')}
                  >{word}</View>
                ))
              }
            </View>
          </>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={7}>
          <>
            <View className={[TemplateStyle['icon-story'], 'animated delay-300 duration-long', index == 6 ? 'scale-to-normal' : ''].join(' ')} />
            <View className={TemplateStyle['layout-grid']}>
              <Image 
                mode='aspectFill'
                className={[TemplateStyle['avatar'], 'animated delay-300 duration-long', index == 6 ? 'translate-x-left' : ''].join(' ')} 
                src={pages[6].avatar || ''} 
              />
              <View className={TemplateStyle.row}>
                <View className={[TemplateStyle.title, 'animated delay-600 duration-long', index == 6 ? 'translate-y-up' : ''].join(' ')}>- 婚礼安排 -</View>
                {
                  pages[6].data && pages[6].data.map((data, dataIndex) => (
                    <View 
                      key={data.title}
                      className={[
                        TemplateStyle[data.style],
                        `animated delay-${7 + dataIndex}00 duration-long`,
                        index == 6 ? 'translate-y-up' : ''
                      ].join(' ')}
                    >{data.title}</View>    
                  ))
                }
                <Image
                  className={[
                    TemplateStyle['circle-image'], 
                    'animated delay-1200 duration-long', 
                    index == 6 ? 'scale-to-normal' : ''
                  ].join(' ')}
                  src={pages[6].circle || ''}
                />
              </View>
            </View>
          </>
        </GoldenTemplateFrame>
        <GoldenTemplateFrame pageIndex={8}>
          <View className={[TemplateStyle['icon-story'], 'animated delay-300 duration-long', index == 7 ? 'scale-to-normal' : ''].join(' ')} />
          <Map
            className={[TemplateStyle.map, 'animated delay-300 duration-long', index == 7 ? 'scale-to-normal' : ''].join(' ')}
            longitude={position.longitude} 
            latitude={position.latitude} 
            onClick={_ => handleOpenMap()}
          />
          <View className={TemplateStyle['row-wrap']}>
            <Button 
              onClick={() => handleMakePhoneCall(bride.phone)} 
              className={[TemplateStyle['btn-phone'], 'animated delay-1400 duration-long', index == 7 ? 'translate-x-right' : ''].join(' ')}
            >
              新娘电话
            </Button>
            <Button 
              onClick={() => handleMakePhoneCall(groom.phone)} 
              className={[TemplateStyle['btn-phone'], 'animated delay-1400 duration-long', index == 7 ? 'translate-x-left' : ''].join(' ')}
            >
              新郎电话
            </Button>
          </View>
          <View className={[TemplateStyle['row-wrap'], TemplateStyle['column']].join(' ')}>
            <View className={[TemplateStyle.row, 'animated delay-800 duration-long', index == 7 ? 'translate-y-up' : ''].join(' ')}>{timeDate}</View>
            <View className={[TemplateStyle.row, 'animated delay-900 duration-long', index == 7 ? 'translate-y-up' : ''].join(' ')}>{position.detail}</View>
            <View className={[TemplateStyle.row, 'animated delay-1000 duration-long', index == 7 ? 'translate-y-up' : ''].join(' ')}>欢迎参加我们的婚礼！</View>
            <View className={[TemplateStyle.row, 'animated delay-1100 duration-long', index == 7 ? 'translate-y-up' : ''].join(' ')}>WELCOME TO MY WEDDING</View>
            <View className={[TemplateStyle.footer, 'animated delay-500 duration-long', index == 7 ? 'scale-to-normal' : ''].join(' ')}>- 敬备喜酌   恭请光临 -</View>
          </View>
        </GoldenTemplateFrame>
      </Swiper>
      { // 如果当前是最后一个，则不展示滚动到下一个按钮
        index == 7 ? null : <View className={[TemplateStyle.arrow, 'animated', 'infinite', 'transform-up-normal'].join(' ')} onClick={() => setSwiperIndexThrottle(index + 1)} />
      }
    </SwiperContext.Provider>
  );
}

function debounce(fn, wait) {
  let timer: any = null
  return function(...args) {
    if(timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(_ => fn(...args), wait)
  }
}

export default React.memo(Template)
